package metrics

import (
	"log"
	"net"
	"strconv"
	"suber-exporter/cmd"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/prometheus/client_golang/prometheus"
	"golang.org/x/exp/rand"
)

var GaugeMetric = prometheus.NewGaugeVec(
	prometheus.GaugeOpts{
		Name: "suber_example_gauge",
		Help: "一个带有标签的 gauge 类型指标.",
	},
	[]string{"selfIP"}, // 定义标签名称
)
var timeStep = cmd.NewK8sConfig().Conf.TimeStep

func Gauge(ctx *gin.Engine) {
	// 创建一个Gauge指标
	timeStepInt, _ := strconv.Atoi(timeStep)
	// 设置随机数种子
	seed := uint64(time.Now().UnixNano())
	rand.Seed(uint64(seed)) // 再转换回 int64 类型传递给 rand.Seed()

	// 生成0.00到10000.00之间的随机浮点数
	randomFloat := rand.Float64() * 10000

	//  获取当前ip
	addrs, _ := net.InterfaceAddrs()

	selfIP := ""
	for _, addr := range addrs {
		// 检查 IP 地址是否为回环地址
		if ipnet, ok := addr.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
			if ipnet.IP.To4() != nil { // 优先返回 IPv4
				selfIP = ipnet.IP.String()
			}
		}
	}
	go func() {
		for {
			// 设置指标值
			GaugeMetric.WithLabelValues(selfIP).Set(randomFloat)
			log.Printf("MustRegister 随机浮点数: %.2f\n", randomFloat) // 保留两位小数输出
			time.Sleep(time.Duration(timeStepInt) * time.Second)
		}
	}()

}
